package org.fuyd.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {
  public static void main(String[] args) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    map.put("username", "a岁的法国各大公司");
    map.put("password", "b");
    System.out.println(post(map, "http://localhost:8080/restaurant/servlet/Test"));
  }

  /**
   * post方法
   * 
   * @param map key为servelt所需的参数，value为所传的值
   * @param postUrl servlet地址
   * @return servlet返回的字符串
   * @throws IOException
   */
  public static String post(Map<String, String> map, String postUrl) throws IOException {
    // 解析map中的参数
    StringBuffer sb = new StringBuffer();
    for (String key : map.keySet()) {
      sb.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&");
    }
    String param = sb.toString().substring(0, sb.toString().length() - 1);
    byte p[] = param.getBytes();

    // 获取servelt的connection
    URL url = new URL(postUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // 设置connection的属性
    connection.setAllowUserInteraction(true);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    connection.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
    connection.setRequestMethod("POST");

    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(p);

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream inputStream = connection.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      String line = null;
      StringBuffer stringBuffer = new StringBuffer();
      while ((line = reader.readLine()) != null) {
        stringBuffer.append(line + "\n");
      }
      return stringBuffer.toString();
    } else {
      return null;
    }
  }
}
